package com;

import com.lhd.bean.Colinfo;
import com.lhd.thread.MyThread;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.List;

import lombok.extern.slf4j.Slf4j;


/**
 * <p>
 * 生成某个表的txt数据. 使用方法：java -cp GenTestData.jar WriteTabTxt {TableName}
 * {ThreadNum}
 *
 * @author MapLover
 * @since 2020.09
 */
@Slf4j
public class Main {
    
    /**
     * @param tabname   表名
     * @param treadNum  线程数（并发数）
     * @param totalRows 总行数
     */
    public static synchronized  void INIT(String tabname, String treadNum, String totalRows) throws InterruptedException {
        
        int iTreadNum = Integer.parseInt(treadNum);
        int iTotalRows = Integer.parseInt(totalRows);

        Thread[] threads = new Thread[iTreadNum];

        List<Colinfo> collist = Colinfo.getColinfo(tabname);

        log.info(tabname + " 开始造数...............");

        String filePath = tabname + ".txt";

        long start = System.currentTimeMillis();//开始计时


        for (int i = 0; i < iTreadNum; i++) {
            MyThread myThread1 = new MyThread(filePath, collist, iTreadNum, i, iTotalRows);
            threads[i] = new Thread(myThread1);
            threads[i].setName(tabname + " 线程" + i);
            threads[i].start();
        }

        for (int i = 0; i < threads.length; i++) {
            threads[i].join();
        }
        
        
        long end = System.currentTimeMillis();//结束计时
        log.info(tabname + " 耗时:" + (end - start) / 1000 + "秒");
        log.info(tabname + " 结束造数...............");
    }

    public static void main(String[] args) throws IOException {
        if (args.length != 2) {
            System.out.println("使用方法:java -cp GenTestDataAnt.jar com.Main {并发数} {总行数}");
            System.out.println("例如:10个并发生成数据，总数为1000笔：");
            System.out.println("java -cp GenTestDataAnt.jar com.Main 10 1000");
        } else {
            
            File f = new File("conf/tablist.txt");
            FileReader fre = new FileReader(f);
            try (BufferedReader bre = new BufferedReader(fre)) {
                String tabname = "";
                while ((tabname = bre.readLine()) != null) //判断最后一行不存在，为空
                {

                    INIT(tabname, args[0], args[1]);

                }
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
                Thread.currentThread().interrupt();
            }finally {

                fre.close();
            }

        }

    }

}